package cn.yogehaoren.foxgitstarter.controller;

import cn.yogehaoren.foxgitstarter.callback.WebHookCallBack;
import cn.yogehaoren.foxgitstarter.properties.GitProperties;
import cn.yogehaoren.foxgitstarter.git.FoxGitService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author WangNing
 * date  2021/7/17 13:31
 * @version 1.0
 */
@RestController("foxHoleController")
@Slf4j
public class FoxGitController {

    @Autowired
    private GitProperties gitProperties;

    @Autowired
    private FoxGitService gitService;


    @Autowired(required = false)
    private WebHookCallBack webHookCallBack;


    /**
     * 处理 WebHook 内容
     * @param request -
     * @param response -
     * @param webHookContent -
     * @return -
     */
    public ResponseEntity handleWebHook(HttpServletRequest request,
                                         HttpServletResponse response,
                                         @RequestBody String webHookContent){
        log.info("Get foxHole webHook Message from: {}", JSONObject.toJSONString(request.getRemoteAddr()));
        String webHookToken = request.getHeader(gitProperties.getWebHookHeader());
        if(StringUtils.isEmpty(webHookToken)){
            log.warn("WebHook Token is None");
            return ResponseEntity.status(403).body("Token is not valid!");
        }else if(gitProperties.getWebHookToken().equals(webHookToken)){
            if(gitProperties.getAutoPull()){
                if(gitProperties.getForcePull()){
                    gitService.forcePullRepository();
                }else {
                    gitService.pullRepository();
                }

            }
            if(webHookCallBack != null){
                webHookCallBack.processWebHook(webHookContent);
            }
            return ResponseEntity.ok("Fox Hole FreshSuccess!");
        }

        return ResponseEntity.status(403).body("Forbidden!");



    }


}
